package com.muyan.netty.nettysocket;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * netty nio客户端示例
 */
public class Client {

    public static void main(String[] args) {
        //启动类
        Bootstrap bootstrap = new Bootstrap();
        //工作线程
        EventLoopGroup worker = new NioEventLoopGroup();

        try {
            //设置线程池
            bootstrap.group(worker);

            //设置socket工厂
            bootstrap.channel(NioSocketChannel.class);

            //设置管道
            bootstrap.handler(new ChannelInitializer<Channel>() {

                @Override
                protected void initChannel(Channel ch) {
                    ch.pipeline().addLast(new StringDecoder())
                            .addLast(new StringEncoder())
                            .addLast(new ClientHandler());
                }
            });

            ChannelFuture future = bootstrap.connect("127.0.0.1", 10101);

            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
            while (true) {
                System.out.println("请输入：");
                String msg = reader.readLine();
                future.channel().writeAndFlush(msg);
            }
        } catch (Exception ignore) {

        } finally {
            worker.shutdownGracefully();
        }


    }

}
